import { message } from 'ant-design-vue'
import { storage } from 'g6-fn'
import { defineStore } from 'pinia'
import { computed, ref, watch } from 'vue'
import { useRouter } from 'vue-router'

import { useFileTaskStore } from '@/components/FileTaskCard/upload-store'
import { menuApi, modelLibraryApi, personalApi } from '@/services/api'
import { getShortName, SSE } from '@/utils'
import { CODE_CLEAR_TASK } from '@/utils/SSE/code'

export interface UserInfo {
  /**
   * 枚举说明: UNAUTHORIZED :未认证 1
   * UNDER_REVIEW :审核中 2
   * AUTHENTICATION :已认证 3
   */
  authenticationStatus?: string
  /**
   * 租户id
   */
  bizId?: string
  /**
   * 主动创建时间
   */
  createTime?: string
  /**
   * 用户描述
   */
  description?: string
  /**
   * 邮箱地址
   */
  email?: string
  /**
   * 用户 id
   */
  id?: number
  /**
   * 枚举说明: NOTCHANGED :未修改 0
   * CHANGED :已修改 1
   */
  isUpdatePwd?: string
  /**
   * 密码
   */
  password?: string
  /**
   * 编号
   */
  serialNumber?: string
  /**
   * 枚举说明: FALSE :禁用 0
   * TRUE :可用 1
   */
  status?: string
  /**
   * 手机号
   */
  tel?: string
  /**
   * 修改密码操作的时间
   */
  updatePwdTime?: string
  /**
   * 被动更新时间
   */
  updateTime?: string
  /**
   * 姓名
   */
  username?: string
  roleType?: number
}

export const useUserInfoStore = defineStore(
  'userInfoStore',
  () => {
    const router = useRouter()
    /* 用户信息 ----------------------------------------------------------------------------------------- */
    const userInfo = ref<UserInfo>({
      isUpdatePwd: '',
      username: ''
    })
    const userNameLastTwo = computed(() => getShortName(userInfo.value.username || ''))

    const changeToken = (token: string) => {
      storage.set('token', token)
    }

    async function getUserInfo() {
      const res = await personalApi.userToken()
      changeUserInfo(res.data)
    }
    function changeUserInfo(data: UserInfo) {
      console.log(data, 'data')
      userInfo.value = data
    }
    async function logout() {
      const fileTaskStore = useFileTaskStore()
      await fileTaskStore.reset()
      await checkTheUploadList()
      $reset()
      router.push('/login')
    }

    const authList = ref([])
    function setAuthList(data: any) {
      authList.value = data
      storage.set('authList', data)
    }

    const getMenuData = async () => {
      const res = await menuApi.allMenuData()
      const { codeList: authList } = res.data
      setAuthList(authList)
      // setMenuTree(menuTree)
    }
    const checkTheUploadList = async (): Promise<void> => {
      // 检查 localStorage 中是否存在 'uploadModelFile' 这个键
      const storedParams = storage.get('uploadModelFile')
      // console.log(storedParams, '000')

      if (storedParams) {
        try {
          const params = storedParams
          console.log(params, 'storedParams')
          // 调用后端的上传完成接口
          const { data } = await modelLibraryApi.deleteNotUploaded(params, {
            isAddUid: true
          })

          if (data) {
            storage.remove('uploadModelFile')
            console.log('删除成功')
          }
          //
        } catch (error) {}
      }
    }

    /* 用户链接相关 ---------------------------------------------------------------------------------------------*/
    const webkitCode = ref('')

    const sse = new SSE({
      messageCb: (code, text) => {
        message.error(text)
        //密码被修改淸除本地信息
        if (code === 'AUTH-100041') {
          $reset()
        }
        closeLink()
        storage.remove('isFirstLogin')
        // 清除用户信息
        router.push('/login')
        if (CODE_CLEAR_TASK.includes(code)) {
          const fileTaskStore = useFileTaskStore()
          fileTaskStore.reset()
        }
      },
      errorCb: error => {
        console.log(error, 'error')
      }
    })

    // 开启链接
    const selectAndLink = (code = '') => {
      webkitCode.value = code || webkitCode.value
      sse.selectAndLink(`/api/cloud/bus/sse/connect?gToken=${webkitCode.value}`)
    }

    const closeLink = () => {
      sse?.closeLink()
    }

    watch(webkitCode, val => {
      if (val === '') {
        console.log('关闭sse')
        closeLink()
      }
    })
    /*  ---------------------------------------------------------------------------------------------*/
    function $reset() {
      changeUserInfo({})
      storage.clear()
      closeLink()
    }

    return {
      userInfo,
      userNameLastTwo,
      changeUserInfo,
      $reset,
      logout,
      getUserInfo,
      getMenuData,
      selectAndLink,
      closeLink,
      changeToken
    }
  },
  {
    persist: true //开启本地持久化存储
  }
)
